package top.hidoctor.auscultation.feature.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.ShaichaAdapter;
import top.hidoctor.auscultation.adapter.ShaixuanAdapter;
import top.hidoctor.auscultation.base.BaseFragment;
import top.hidoctor.auscultation.bean.ShaichaBean;
import top.hidoctor.auscultation.bean.ShaixuanBean;
import top.hidoctor.auscultation.event.AssessEvent;
import top.hidoctor.auscultation.event.XinyinEvent;
import top.hidoctor.auscultation.feature.activity.ShaichaDetailActivity;
import top.hidoctor.auscultation.net.c.ScreeningReq;
import top.hidoctor.auscultation.net.c.ShaichaListContract;
import top.hidoctor.auscultation.net.p.ShaichaListPresenter;
import top.hidoctor.auscultation.net.req.ShaichaReq;

public class ShaichaFragment extends BaseFragment implements View.OnClickListener, ShaichaListContract.View {

    private RecyclerView rcShaicha;
    private TextView tvShaixuan;
    private DrawerLayout drawer;
    private ShaichaAdapter adapter;
    private EditText editSearch;
    private List<ShaixuanBean> shaixuanBeanList = new ArrayList<>();
    private Button btnChongzhi, btnConfirm;
    private ShaixuanAdapter shaixuanAdapter;
    private RecyclerView rcCondition;
    private SwipeRefreshLayout refreshLayout;
    private ShaichaListPresenter presenter;
    private ShaichaReq req;
    private ScreeningReq screeningReq;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shaicha, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        presenter = new ShaichaListPresenter(getContext(), this);
        req = new ShaichaReq();
        screeningReq = new ScreeningReq();
        initView();
    }

    private void initView() {
        drawer = getActivity().findViewById(R.id.drawer);
        refreshLayout = getActivity().findViewById(R.id.refreshLayout_shaicha);
        tvShaixuan = getActivity().findViewById(R.id.tv_shaixuan_s);
        rcShaicha = getActivity().findViewById(R.id.rc_shaicha);
        editSearch = getActivity().findViewById(R.id.edit_search_shaicha);
        rcShaicha.setLayoutManager(new LinearLayoutManager(getContext()));
        rcShaicha.setAdapter(adapter = new ShaichaAdapter(R.layout.item_shaicha, null));
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_empty_list, (ViewGroup) rcShaicha.getParent(), false);
        adapter.setEmptyView(view);
        adapter.isFirstOnly(false);
        adapter.openLoadAnimation();
        adapter.openLoadMore(10, true);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hideSoft(refreshLayout);
                req.setKeyWord(editSearch.getText().toString().trim());
                refresh();
            }
        });

        adapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ShaichaBean.ResultBean bean = (ShaichaBean.ResultBean) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.ll_content:
                        startActivity(new Intent(getContext(), ShaichaDetailActivity.class).putExtra("id", bean.getId()));
                        break;
                    case R.id.fl_ai:
                        if (bean.getAiStatus() == 10) {
                            startActivity(new Intent(getContext(), ShaichaDetailActivity.class).putExtra("id", bean.getId()));
                        } else {// 重新分析
                            screeningReq.setId(bean.getId());
                            screeningReq.setAiStatus(10);
                            presenter.screenUpdate(bean.getId(), screeningReq);
                        }

                        break;
                }
            }
        });
        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            req.setKeyWord(v.getText().toString().trim());
                            refresh();
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        tvShaixuan.setOnClickListener(this);
        initDrawer();
        refresh();
    }

    private void loadMore() {
        req.setPageNo(1 + req.getPageNo());
        presenter.getList(req, refreshLayout);
    }

    private void refresh() {
        req.setPageNo(1);
        presenter.getList(req, refreshLayout);
    }


    private void initDrawer() {
        shaixuanBeanList.add(new ShaixuanBean(false, "筛查中", "10"));
        shaixuanBeanList.add(new ShaixuanBean(false, "筛查完成", "20"));
        shaixuanBeanList.add(new ShaixuanBean(false, "筛查失败", "30"));
        drawer = getActivity().findViewById(R.id.drawer_shaixuan);
        rcCondition = getActivity().findViewById(R.id.rc_content);
        btnChongzhi = getActivity().findViewById(R.id.btn_reset);
        btnConfirm = getActivity().findViewById(R.id.btn_ok);
        rcCondition.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rcCondition.setAdapter(shaixuanAdapter = new ShaixuanAdapter(R.layout.item_shaixuan, shaixuanBeanList));
        btnConfirm.setOnClickListener(this);
        btnChongzhi.setOnClickListener(this);
        shaixuanAdapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<ShaixuanBean> data = adapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setCheck(false);
                }
                data.get(position).setCheck(true);
                adapter.notifyDataSetChanged();
                req.setStatus(data.get(position).getStatus());
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_shaixuan_s:
                hideSoft(tvShaixuan);
                drawer.openDrawer(Gravity.RIGHT);
                break;
            case R.id.btn_reset:
                List<ShaixuanBean> shaixuanList = shaixuanAdapter.getData();
                for (int i = 0; i < shaixuanList.size(); i++) {
                    shaixuanList.get(i).setCheck(false);
                }
                shaixuanAdapter.notifyDataSetChanged();
                drawer.closeDrawer(Gravity.RIGHT);
                editSearch.setText("");
                req.setStatus("");
                req.setKeyWord("");
                refresh();
                break;
            case R.id.btn_ok:
                drawer.closeDrawer(Gravity.RIGHT);
                editSearch.setText("");
                req.setKeyWord("");
                refresh();
                break;
        }
    }

    @Override
    public void getListSuc(ShaichaBean bean) {
        if (req.getPageNo() == 1) {
            refreshLayout.setRefreshing(false);
            adapter.setNewData(bean.getResult());
        } else {
            adapter.addData(bean.getResult());
        }
        adapter.openLoadMore(bean.getTotalItems() > adapter.getItemCount());
    }

    @Override
    public void screenUpdateSuc() {
        refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AssessEvent event) {
        editSearch.setText("");
        req.setKeyWord("");
        refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(XinyinEvent event) {
        editSearch.setText("");
        req.setKeyWord("");
        refresh();
    }

    @Override
    public void onError(String code, String msg) {
        super.onError(code, msg);
        showToast(msg);
        refreshLayout.setRefreshing(false);
    }
}
